package com.hc.appanimal;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.hc.DTO.AnimalCategoryMasterDTO;
import com.hc.DTO.AnimalDTO;
import com.hc.adapter.AnimalAdapter;
import com.hc.common.ActionEvent;
import com.hc.constants.Constants;
import com.hc.controller.AnimalController;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class AnimalActivity extends Activity implements OnItemClickListener,
		OnClickListener {
	// ViewStub listview, gridview;
	// private ListView list;
	private GridView grid;
	ArrayList<Object> arrData;
	AnimalAdapter adapter;
	// AnimalListAdapter Listadapter;
	TextView txtTitle;
	Button btnBack;
	EditText edSearchName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_animal);

		arrData = new ArrayList<Object>();
		txtTitle = (TextView) findViewById(R.id.txtTitle);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setVisibility(View.VISIBLE);
		btnBack.setOnClickListener(this);
		Bundle data = getIntent().getExtras();
		int key = data.getInt("Search");
		if (key == 1) {
			String keySearch = data.getString("keyseach");
			Bundle data1 = new Bundle();
			data1.putString("keyseach", keySearch);
			InitData1(data1);
			txtTitle.setText("Animal");
		} else if (key == 2) {
			AnimalCategoryMasterDTO dto = (AnimalCategoryMasterDTO) data
					.getSerializable("animal");
			Bundle dataId = new Bundle();
			dataId.putInt("idAnimal", dto.getId());
			InitData(dataId);
			txtTitle.setText(dto.getAnimalCategory());
		}

		// gridview = (ViewStub) findViewById(R.id.grid);
		// listview = (ViewStub) findViewById(R.id.list);
		//
		// listview.inflate();
		// gridview.inflate();
		// list = (ListView) findViewById(R.id.list);
		grid = (GridView) findViewById(R.id.grid);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels;
		int height = dm.heightPixels;
		int dens = dm.densityDpi;
		double wi = (double) width / (double) dens;
		double hi = (double) height / (double) dens;
		double x = Math.pow(wi, 2);
		double y = Math.pow(hi, 2);
		double screenInches = Math.sqrt(x + y);

		if (screenInches >= 4.0) {
			grid.setNumColumns(3);
		} else {
			grid.setNumColumns(2);
		}
		initImageLoader(getApplicationContext());
		adapter = new AnimalAdapter(this, R.layout.grid_row, arrData);

		grid.setAdapter(adapter);
		grid.setOnItemClickListener(this);
		// setAdapters();

		edSearchName = (EditText) findViewById(R.id.edSearchName);

		edSearchName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!newArr.contains(null)) {
					String text = edSearchName.getText().toString()
							.toLowerCase(Locale.getDefault());
					filter(text);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		// Checks the orientation of the screen
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			grid.setNumColumns(3);

		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			DisplayMetrics dm = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(dm);
			int width = dm.widthPixels;
			int height = dm.heightPixels;
			int dens = dm.densityDpi;
			double wi = (double) width / (double) dens;
			double hi = (double) height / (double) dens;
			double x = Math.pow(wi, 2);
			double y = Math.pow(hi, 2);
			double screenInches = Math.sqrt(x + y);

			if (screenInches >= 4.0) {
				grid.setNumColumns(3);
			} else {
				grid.setNumColumns(2);
			}
		}
	}

	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.diskCacheSize(50 * 1024 * 1024)
				// 50 Mb
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}

	public void filter(String charText) {
		charText = charText.toLowerCase(Locale.getDefault());
		arrData.clear();
		if (charText.length() == 0) {
			arrData.addAll(newArr);
			adapter.notifyDataSetChanged();
		} else {
			for (AnimalDTO contacts : newArr) {
				if (contacts.getCommonName().toLowerCase(Locale.getDefault())
						.contains(charText)) {
					arrData.add(contacts);
					adapter.notifyDataSetChanged();
				}
			}
		}

	}

	// private void setAdapters() {
	// adapter = new AnimalAdapter(AnimalActivity.this, R.layout.grid_row,
	// arrData);
	// grid.setAdapter(adapter);
	// grid.setOnItemClickListener(this);
	//
	// // if (list_visibile) {
	// // Listadapter = new AnimalListAdapter(AnimalActivity.this,
	// // R.layout.list_row, arrData);
	// // list.setAdapter(Listadapter);
	// // list.setOnItemClickListener(this);
	// // }
	// //
	// // else {
	// // adapter = new AnimalAdapter(AnimalActivity.this, R.layout.grid_row,
	// // arrData);
	// // grid.setAdapter(adapter);
	// // grid.setOnItemClickListener(this);
	// // }
	//
	// }

	// private void changeView() {
	//
	// // if the current view is the listview, passes to gridview
	// if (list_visibile) {
	// // btnList.setBackgroundResource(R.drawable.list);
	// listview.setVisibility(View.GONE);
	// gridview.setVisibility(View.VISIBLE);
	// list_visibile = false;
	// setAdapters();
	// }
	//
	// else {
	// // btnList.setBackgroundResource(R.drawable.listf);
	// gridview.setVisibility(View.GONE);
	// listview.setVisibility(View.VISIBLE);
	// list_visibile = true;
	// setAdapters();
	// }
	//
	// }

	public void InitData(Bundle data) {
		ActionEvent e = new ActionEvent(AnimalActivity.this,
				Constants.GET_ANIMAL_BY_CATEGORY, null, data);
		AnimalController.getInstance().handleViewEvent(e);
	}

	public void InitData1(Bundle data) {
		ActionEvent e = new ActionEvent(AnimalActivity.this,
				Constants.GET_ANIMAL_BY_STRING, null, data);
		AnimalController.getInstance().handleViewEvent(e);
	}

	ArrayList<AnimalDTO> newArr;

	@SuppressWarnings("unchecked")
	public void handleControllerViewEvent(ActionEvent e) {
		switch (e.action) {
		case Constants.GET_ANIMAL_BY_CATEGORY:
			newArr = (ArrayList<AnimalDTO>) e.viewData;
			new VerySlowTask(newArr).execute();
			break;

		case Constants.GET_ANIMAL_BY_STRING:
			newArr = (ArrayList<AnimalDTO>) e.viewData;
			new VerySlowTask(newArr).execute();
			break;
		default:
			break;
		}
	}

	// sysAnimal
	public class VerySlowTask extends AsyncTask<String, Object, Void> {
		List<AnimalDTO> _newArr;

		public VerySlowTask(List<AnimalDTO> arr) {
			_newArr = arr;
		}

		@Override
		protected Void doInBackground(String... params) {
			try {
				for (int i = 0; i < _newArr.size(); i++) {
					try {
						publishProgress(_newArr.get(i));
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Object... values) {
			arrData.add(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			adapter.notifyDataSetChanged();
			// if (list_visibile) {
			// Listadapter.notifyDataSetChanged();
			//
			// } else {
			// adapter.notifyDataSetChanged();
			// }
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			AnimalDTO dto = (AnimalDTO) grid.getItemAtPosition(position);
			Intent intent = new Intent(AnimalActivity.this,
					SummaryActivity.class);
			Bundle data = new Bundle();
			data.putSerializable("images", dto);
			intent.putExtras(data);
			startActivity(intent);
		} catch (Exception e) {
			// TODO: handle exception
		}
		// if (list_visibile) {
		// try {
		// AnimalDTO dto = (AnimalDTO) list.getItemAtPosition(position);
		// Intent intent = new Intent(AnimalActivity.this,
		// DetailAnimalActivity.class);
		// Bundle data = new Bundle();
		// data.putSerializable("detail", dto);
		// data.putSerializable("token", tokenDTO);
		// intent.putExtras(data);
		// startActivity(intent);
		//
		// } catch (Exception e) {
		// // TODO: handle exception
		// }
		//
		// } else {
		// try {
		// AnimalDTO dto = (AnimalDTO) grid.getItemAtPosition(position);
		// Intent intent = new Intent(AnimalActivity.this,
		// DetailAnimalActivity.class);
		// Bundle data = new Bundle();
		// data.putSerializable("detail", dto);
		// data.putSerializable("token", tokenDTO);
		// intent.putExtras(data);
		// startActivity(intent);
		// } catch (Exception e) {
		// // TODO: handle exception
		// }
		// }

	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.btnBack:
			finish();
			break;

		case R.id.img_view_push_messages:
			intent = new Intent(AnimalActivity.this, ViewMessageActivity.class);
			startActivity(intent);
			finish();
			break;

		case R.id.img_new_push_message:
			intent = new Intent(AnimalActivity.this, UpdateAnimalActivity.class);
			startActivity(intent);
			finish();
			break;

		default:
			break;
		}

	}
}
